package com.github.shiqiyue.xm.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.shiqiyue.xm.entity.Company;
import com.github.shiqiyue.xm.enums.CompanyStatus;
import com.github.shiqiyue.xm.enums.ConfigKeys;
import com.github.shiqiyue.xm.mapper.CompanyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/***
 *
 * @author wenyao.wu
 * @date 2019/8/9
 */
@Service
public class CompanyService {

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private ConfigService configService;



    //@CacheEvict(cacheNames = "company", allEntries = true)
    public void add(Company company) {
        if("1".equals(configService.getValueByKey(ConfigKeys.NEED_AUDIT.getName()))){
            company.setStatus(CompanyStatus.WAIT_AUDIT);
        }else{
            company.setStatus(CompanyStatus.VALID);
        }
        companyMapper.insert(company);
    }

   // @Cacheable(cacheNames = "company")
    public IPage<Company> page(Integer currentPage, Integer pageSize, String name) {
        Page page = new Page(currentPage, pageSize);
        QueryWrapper queryWrapper = new QueryWrapper();
        if (!StringUtils.isEmpty(name)) {
            queryWrapper.like("name", name);
        }
        queryWrapper.eq("status", CompanyStatus.VALID);
        return companyMapper.selectPage(page, queryWrapper);
    }

    public IPage<Company> managePage(Integer currentPage, Integer pageSize, String name) {
        Page page = new Page(currentPage, pageSize);
        QueryWrapper queryWrapper = new QueryWrapper();
        if (!StringUtils.isEmpty(name)) {
            queryWrapper.like("name", name);
        }
        queryWrapper.ne("status", CompanyStatus.NOT_VALID);
        return companyMapper.selectPage(page, queryWrapper);
    }

   // @CacheEvict(cacheNames = "company", allEntries = true)
    public void updateStatus(Long id, CompanyStatus companyStatus){
        Company company = new Company();
        company.setId(id);
        company.setStatus(companyStatus);
        companyMapper.updateById(company);
    }


}
